<?php
if($admin->isAdmin('admin', 'manager') == true) {
if($_GET['tpage']) {
$page = $_GET['tpage'];

function file_get_contents_utf8($fn) {
     $content = file_get_contents($fn);
      return mb_convert_encoding($content, 'UTF-8',
          mb_detect_encoding($content, 'UTF-8, ISO-8859-1', true));
} 
preg_replace('/\//', '', $page, 1);
echo (file_get_contents_utf8(BASE_URL.$page));
exit();
}
if($_GET['upload'] == 'true') {
	function findexts ($filename) {
		$filename = strtolower($filename);
		$exts = explode(".", $filename);
		$n = count($exts)-1;
		$exts[$n] = ""; 
		$exts = implode($exts, ".");
		$exts = substr($exts, 0, -1);
		return trim($exts); 
	}
	$filename = sha1(time());
	$target = BASE_URL.'temp/'.$filename.'.zip';
	if($_FILES['utheme']['type'] != "application/zip" || findexts($_FILES['utheme']['name'] != "zip")) {
		$file = findexts($_FILES['utheme']['name'] != "zip");

		$mess .= $admin->message('error', 'Oh no! The file you uploaded isn\'t a zip file!', "You uploaded a {$_FILES['utheme']['type']}, {$file} file. Please try uploading again!");
	}
	else {
		$text = move_uploaded_file($_FILES['utheme']['tmp_name'], $target);
		if($text) {
			$ok = 1;
			if ($_FILES['utheme']['size'] > 8000000) {
				$mess .= $admin->message('error', 'Oh no! The upload failed!', 'Your file was too large.');
				$ok=0;
			}
			else {
				$install = new themeInstaller($filename.'.zip');
				$test = $install->test($filename.'.zip');
				if($test == true) {
					$dest = BASE_URL.'temp/'.$_POST['theme-name'].'.zip';
					copy($target, $dest);
					unlink(BASE_URL.'temp/'.$filename.'.zip');
					$qwer = $install->install($_POST['theme-name'], true);
					$mess .= $admin->message('succes', 'Woohoo! Your theme was successfully installed!', 'You can now apply it using the form below.');
				}
				elseif ($test == false) {
					$mess .= $admin->message('error', 'Oh no! The theme didn\'t pass testing!', 'Something went funny on the server. Try uploading it again. If it doesn\'t work, upload the theme via FTP.');
				}
				else {
					$mess .= $test;
				}
			}
		} 
		else {
			$mess .= $admin->message('error', 'Oh no! The upload failed!', 'Something went funny on the server. Try uploading it again. If it doesn\'t work, upload the theme via FTP.');
			$ok = 0;
		}
	}
}
if(isset($_POST['save'])) {
	$query = $admin->db_query("UPDATE ".DBTABLEPREFIX."settings_site SET value = '".mysql_real_escape_string($_POST['Theme'])."' WHERE settingname = 'Theme'");
	if(!$query) {
		$output .= $admin->message('error', 'MySQL Error', mysql_error());
	}
	else {
		$output .= $admin->message('success', "Woohoo! Theme changed to ".mysql_real_escape_string($_POST['Theme']), "Click 'view site' in the upper right hand corner if you want to see the theme in action");
	}
}

if($_POST['tpage']) {
	$page = $_POST['tpage'];
	$content =$_POST['content'];
	$content = stripslashes(stripslashes(preg_replace('/%([0-9a-f]{2})/ie', "chr(hexdec('\\1'))", $content)));
	$file = BASE_URL.$page;
	$fh = fopen($file, 'w') or die("can't open file");
	fwrite($fh, $content);
	fclose($fh);
	echo $admin->message('success', 'Changes were applied.', 'The file: '.$page.' was saved at '.date('g:i:s').'.');
	exit();
}
$admin->register_site_info();
	$srow['value'] = $admin->getSetting('Theme', true);
	$path = BASE_URL."themes/";
	$settings_form = $settings_form."\n";
	$settings_form = $settings_form."<span><select name='Theme' id='Theme'>";
	//using the opendir function
	$dir_handle = @opendir($path) or die("Unable to open $path");
	//running the while loop
	while ($file = readdir($dir_handle)) {
		if($file!="." && $file!="..") {
			$settings_form = $settings_form."<option value='".$file."'";
			if($file == $srow['value']) {
				$settings_form .= ' selected="selected"';
			}
			$settings_form .= '>'.$file;
			if($file == $srow['value']) {
				$settings_form .= ' (current theme)';
			}			
			$settings_form .= '</option>';
		}
	}
	//closing the directory
	closedir($dir_handle);
	$settings_form = $settings_form."</select></span></div>\n";
	$output .= '							<form id="changeTheme" action="?page=theme-management" method="post">
									<fieldset>
										<h2>Change Theme</h2>
										<div class="form-row">
											<label for="Theme">Theme</label>
												'.$settings_form.'
										<div class="form-row form-row-last">
											<label for="save">Save</label>
											<span><input type="submit" name="save" value="Save Theme" class="submit" /></span>
										</div>
									</fieldset>
								</form>
	';

	$output .= '							<form id="uploadTheme" action="?page=theme-management&upload=true" method="post" enctype="multipart/form-data">
									<fieldset>
										<h2>Upload a new Theme</h2>
										<div class="form-row">
											<label for="utheme">Browse for theme zip file (.zip)</label>
											<span><input type="file" name="utheme" /></span>
										</div>
										<div class="form-row">
											<label for="theme-name">Name of the Theme<span class="small gray">Alphanumeric characters, spaces and dots (.), only please.</span></label>
											<span><input type="text" name="theme-name" id="theme-name" /></span>
										</div>
										<div class="form-row form-row-last">
											<label for="save">Upload<span class="small gray">Please be patient, this process may take several minutes. Do not leave this page.</span></label>
											<span><input type="submit" name="upload" value="Upload Theme" class="submit" onclick="$(this).attr(\'disabled\', \'disabled\')"/></span>
										</div>
									</fieldset>
								</form>
	';
	function scan_directory_recursively($directory, $filter=FALSE)
	{
		// if the path has a slash at the end we remove it here
		if(substr($directory,-1) == '/')
		{
			$directory = substr($directory,0,-1);
		}

		// if the path is not valid or is not a directory ...
		if(!file_exists($directory) || !is_dir($directory))
		{
			// ... we return false and exit the function
			return FALSE;

		// ... else if the path is readable
		}elseif(is_readable($directory))
		{
			// we open the directory
			$directory_list = opendir($directory);

			// and scan through the items inside
			while (FALSE !== ($file = readdir($directory_list)))
			{
				// if the filepointer is not the current directory
				// or the parent directory
				if($file != '.' && $file != '..')
				{
					// we build the new path to scan
					$path = $directory.'/'.$file;

					// if the path is readable
					if(is_readable($path))
					{
						// we split the new path by directories
						$subdirectories = explode('/',$path);

						// if the new path is a directory
						if(is_dir($path))
						{
							$clean_path = explode($directory.'/', $path, 2);
							$clean_path = $clean_path[1];
							// add the directory details to the file list
							$directory_tree[$clean_path] = scan_directory_recursively($path, $filter);

						// if the new path is a file
						}elseif(is_file($path))
						{
							// get the file extension by taking everything after the last dot
							$extension = end(explode('.',end($subdirectories)));

							// if there is no filter set or the filter is set and matches
							if($filter === FALSE || $filter == $extension)
							{
								// add the file details to the file list
								$dir = $path;
								$path = explode($directory.'/', $path, 2);
								$path = $path[1];
								$directory_tree[] = $path.'&&||&&'.$dir;
							}
						}
					}
				}
			}
			// close the directory
			closedir($directory_list); 

			// return file list
			return $directory_tree;

		// if the path is not readable ...
		}else{
			// ... we return false
			return FALSE;	
		}
	}
	function makeULLI($array) {
		$returnFiles = "<ul>\n";

		if (is_array($array) && count($array) > 0) {
			foreach ($array as $k => $v) {
				if (is_array($v) && count($v) > 0) {
					$returnFiles .= "\t<li class='dir file'>" . $k . '/'. makeULLI($v) . "</li>\n";
				}
				else {
					$dir = explode('&&||&&', $v,2);
					$v = $dir[0];
					$dir = $dir[1];
				$ext = pathinfo($v, PATHINFO_EXTENSION);
					$ok =1;
						switch ($ext) {
							case "js":
								$returnFiles .= "\t<li class='file-js";
								break;
							case "css":
								$returnFiles .= "\t<li class='file-css";
								break;
							case "php":
								$returnFiles .= "\t<li class='file-php";
								break;
							case "tpl":
								$returnFiles .= "\t<li class='file-tpl";
								break;
							case "htm":
								$returnFiles .= "\t<li class='file-html";
								break;
							case "xhtml":
								$returnFiles .= "\t<li class='file-html";
								break;
							case "html":
								$returnFiles .= "\t<li class='file-html";
								break;
							case "txt":
								$returnFiles .= "\t<li class='file-txt";
								break;
							default:
								$ok = 0;
								$returnFiles .= "\t<li class='file-other";
								break;
						}
						if($ok == 0) {
							$returnFiles .= " file'>".$v . "</li>\n";
						}
						else {
							$returnFiles .= " file'><a class='edit-file' href='javascript:;' title='".$dir."'>".$v . "</a></li>\n";
						}
				}
			}
		} else {}

		$returnFiles .= "</ul>";

		return $returnFiles;
	}
	$files = makeULLI(scan_directory_recursively('themes/'.$admin->getSetting('Theme')));	
	$output .= '
								<form action="?page=theme-management" id="formEditTheme" method="post">
									<fieldset>
										<div class="left-col">
											<h2>Edit the Current Theme</h2>
												<br />
												<a class="expand-textbox" href="javascript:;"><img src="includes/admin/images/loading.gif" /></a>
												<h3 id="editing-file-head">Editing: <span>No File</span></h3>
												<div class="msg-box"></div>
											<div class="form-row">
												<label style="width:10%;">Edit</label>
												<span><textarea rows="20" cols="50" name="editTheme" style="width:112%;" id="editTheme"></textarea></span>
											</div>
											<div class="form-row form-row-last">
												<label style="width:10%;">Save</label>
												<span><input type="submit" name="saveFile" value="Save File" class="button" /></span>
											</div>
										</div>
										<div class="right-col">
											<h2>Editable Pages</h2>
											<div id="editable-pages">
												'.$files.'
											</div>
										</div>
										<br class="clear" />
									</fieldset>
								</form>		
	';
}
else {
	$output .= $admin->message('error', "You don't have sufficent permissions.", "You need to be an Admin or a Low-Level Admin to access this page.");
}
$jump = '				<form method="post" action="admin.php?page=settings" id="form-new-setting">
					<fieldset>
						<h2>Jump To:</h2>
						<p>Need to get somewhere fast?</p>
						<ul>
							<li><a href="#changeTheme">Change Theme</a></li>
							<li><a href="#uploadTheme">Upload Theme</a></li>
							<li><a href="#formEditTheme">Edit a theme file</a></li>
						</ul>
					</fieldset>
				</form>
';

$admin->page_info['content']['page_title'] = "Theme Managment";
$admin->page_info['content']['page_content']	= $mess.$jump.$output;
//Display page
include(BASE_URL.'includes/admin/admin.php');
?>